//
//  EXRefreshControl.m
//  Exercise
//
//  Created by 羊谦 on 16/6/20.
//  Copyright © 2016年 NetEase-yangqian. All rights reserved.
//

#import "EXRefreshControl.h"
#import "EXRefreshView.h"

@interface EXRefreshControl ()

@property (nonatomic,strong) EXRefreshView *refreshView;

@end

@implementation EXRefreshControl
{
@private
    BOOL _rotationFlag;//是否旋转箭头
    BOOL _animtoringFlag;//是否执行动画
    BOOL _isLoading;//刷新的时候不再进行其他操作
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _refreshView = [[EXRefreshView alloc] init];
        [self addSubview:_refreshView];
        [_refreshView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(self);
            make.size.mas_equalTo(CGSizeMake(200, 100));
        }];
        
        [self addObserver:self forKeyPath:@"frame" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

-(void)dealloc {
    [self removeObserver:self forKeyPath:@"frame"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    CGFloat y = self.frame.origin.y;
    if (y >= 0 || y == -64)
    {
        return;
    }
    // 2. 判断是否一进来就进行刷新
    if (_beginAnimFlag ) {
        if (!_isLoading) {
            _isLoading = YES;
            _animtoringFlag = YES;
            [self.refreshView beginLoadingAnimator];
        }
        return;
    }
    // 3. 释放已经触发了刷新事件, 如果触发了, 需要进行旋转
    if (self.refreshing && !_animtoringFlag)
    {
        _animtoringFlag = YES;
        [self.refreshView beginLoadingAnimator];
        return;
    }
    
    if (y <= -50 && !_rotationFlag)
    {
        _rotationFlag = YES;
        [self.refreshView rotationRefresh:_rotationFlag];
    }else if((y > -50 && _rotationFlag)) {
        _rotationFlag = NO;
        [self.refreshView rotationRefresh:_rotationFlag];
    }
}

- (void)endRefreshing {
    [super endRefreshing];
    _animtoringFlag = NO;
    _beginAnimFlag = NO;
    _isLoading = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.refreshView stopLoadingAnimator];
    });
}

-(void)beginRefreshing {
    [super beginRefreshing];
    _beginAnimFlag = YES;
}

@end
